package com.neutech.service.impl;

import com.neutech.entity.Order;
import com.neutech.entity.OrderItem;
import com.neutech.entity.Product;
import com.neutech.enumeration.OrderStatusEnum;
import com.neutech.enumeration.ResultExceptionEnum;
import com.neutech.form.CartForm;
import com.neutech.form.OrderForm;
import com.neutech.mapper.OrderMapper;
import com.neutech.pojo.OrderItemPOJO;
import com.neutech.service.CartService;
import com.neutech.service.OrderItemService;
import com.neutech.service.OrderService;
import com.neutech.service.ProductService;
import com.neutech.util.DateUtil;
import com.neutech.vo.OrderVO;
import com.neutech.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {

    private final OrderMapper mapper;
    private final OrderItemService orderItemService;
    private final ProductService productService;
    private final CartService cartService;

    @Autowired
    public OrderServiceImpl(OrderMapper mapper, OrderItemService orderItemService, ProductService productService, CartService cartService) {
        this.mapper = mapper;
        this.orderItemService = orderItemService;
        this.productService = productService;
        this.cartService = cartService;
    }

    @Override
    public ResultVO<OrderVO> getOrderByOrderNo(Long orderNo) {
        if (orderNo == null)
            return ResultVO.error(ResultExceptionEnum.FORMAT_EXCEPTION);

        Order order = mapper.selectByOrderNo(orderNo);

        ResultVO<List<OrderItem>> resultVO = orderItemService.getOrderItemByOrderNo(orderNo);
        if (resultVO.getCode() != 0) return ResultVO.error(resultVO.getCode(), resultVO.getMsg());

        return ResultVO.success(parseOrderToVO(order, resultVO.getData()));
    }

    public ResultVO<List<OrderVO>> getOrderByUserIdAndStatus(Integer userId, Byte orderStatusEnum) {
        if (userId == null) return ResultVO.error(ResultExceptionEnum.FORMAT_EXCEPTION);
        //查询用户对应订单信息
        List<Order> orders = mapper.selectAllByUserIdSelective(userId, orderStatusEnum);
        List<OrderVO> orderVOList = new ArrayList<>();

        for (Order order : orders) {
            ResultVO<List<OrderItem>> resultVO = orderItemService.getOrderItemByOrderNo(order.getOrderNo());
            if (resultVO.getCode() != 0) return ResultVO.error(resultVO.getCode(), resultVO.getMsg());
            orderVOList.add(parseOrderToVO(order, resultVO.getData()));
        }

        return ResultVO.success(orderVOList);
    }

    @Override
    public ResultVO<Void> orderOpenPay(Long orderNo) {
        Order order = mapper.selectByOrderNo(orderNo);
        if (!order.getStatus().equals(OrderStatusEnum.ORDER_UNPAID.getStatusCode()))
            return ResultVO.error(ResultExceptionEnum.ILLEGAL_ACTION);
        return null;
    }

    @Override
    public ResultVO<Void> orderFinishPay(Long orderNo) {
        Order order = mapper.selectByOrderNo(orderNo);
        if (!order.getStatus().equals(OrderStatusEnum.ORDER_UNPAID.getStatusCode()))
            return ResultVO.error(ResultExceptionEnum.ILLEGAL_ACTION);
        return null;
    }

    @Override
    public ResultVO<Void> orderClosePay(Long orderNo) {
        Order order = mapper.selectByOrderNo(orderNo);
        if (!order.getStatus().equals(OrderStatusEnum.ORDER_UNPAID.getStatusCode()))
            return ResultVO.error(ResultExceptionEnum.ILLEGAL_ACTION);
        return null;
    }

    @Override
    public ResultVO<OrderVO> orderCreate(OrderForm orderForm) {
        BigDecimal totalPrice = new BigDecimal(0);
        List<OrderItem> itemList = new ArrayList<>();
        //生成订单号
        long orderNo = ((long) orderForm.getUserId() << 10) + new Date().getTime() + new Random().nextInt(100);

        //注册订单内商品
        for (OrderItemPOJO itemPOJO : orderForm.getItemList()) {
            ResultVO<Product> pResultVO = productService.getProduct(itemPOJO.getProductId());
            if (pResultVO.getCode().equals(ResultExceptionEnum.PRODUCT_NOT_EXIST.getCode()))
                return ResultVO.error(ResultExceptionEnum.DATA_NON_EXISTS);

            Product product = pResultVO.getData();

            int quantity = itemPOJO.getQuantity();
            if (quantity <= 0)
                return ResultVO.error(ResultExceptionEnum.FORMAT_EXCEPTION);

            OrderItem item = parseProductToItem(product, quantity, orderForm.getUserId(), orderNo);
            totalPrice = totalPrice.add(item.getTotalPrice());
            itemList.add(item);
        }

        //批量注册
        if (orderItemService.addOrderItems(itemList).isFail())
            return ResultVO.error(ResultExceptionEnum.UNKNOWN_ERROR_OCCURED);

        //生成订单
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(orderForm.getUserId());
        order.setShippingId(orderForm.getShippingId());
        order.setPayment(totalPrice);
        order.setPaymentType(orderForm.getPaymentType());
        order.setPostage(0);
        order.setCreateTime(new Date());

        if (mapper.insertSelective(order) != 1)
            return ResultVO.error(ResultExceptionEnum.UNKNOWN_ERROR_OCCURED);

        if (cartService.orderItemRemove(parseCartForm(orderForm)).isFail())
            return ResultVO.error(ResultExceptionEnum.UNKNOWN_ERROR_OCCURED);

        return ResultVO.success(parseOrderToVO(order, itemList));
    }

    private OrderItem parseProductToItem(Product product, int quantity, int userId, long orderNo) {
        OrderItem item = new OrderItem();
        item.setUserId(userId);
        item.setOrderNo(orderNo);
        item.setProductId(product.getId());
        item.setProductName(product.getName());
        item.setProductImage(product.getMainImage());

        // 计算总价
        BigDecimal unitPrice = product.getPrice();
        BigDecimal totalPrice = unitPrice.multiply(new BigDecimal(quantity));

        item.setCurrentUnitPrice(unitPrice);
        item.setQuantity(quantity);
        item.setTotalPrice(totalPrice);
        item.setCreateTime(new Date());
        return item;
    }

    private OrderVO parseOrderToVO(Order order, List<OrderItem> itemList) {
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderNo(order.getOrderNo());
        orderVO.setUserId(order.getUserId());
        orderVO.setPayment(order.getPayment());
        orderVO.setPostage(order.getPostage());
        orderVO.setPaymentType(order.getPaymentType());
        orderVO.setOrderStatus(OrderStatusEnum.getStatus(order.getStatus()));
        orderVO.setItems(itemList);
        orderVO.setCreateDate(DateUtil.getTimeString(order.getCreateTime()));
        orderVO.setUpdateDate(DateUtil.getTimeString(order.getUpdateTime()));
        return orderVO;
    }

    private ResultVO<Void> updateResult(int updateCode) {
        switch (updateCode) {
            case 0:
                return ResultVO.error(ResultExceptionEnum.DATA_NON_EXISTS);

            case 1:
                return ResultVO.success();

            default:
                return ResultVO.error(ResultExceptionEnum.UNKNOWN_ERROR_OCCURED);
        }
    }

    private CartForm parseCartForm(OrderForm orderForm) {
        CartForm cartForm = new CartForm();

        List<Integer> productIdList = new ArrayList<>();

        for (OrderItemPOJO item : orderForm.getItemList()) {
            productIdList.add(item.getProductId());
        }

        cartForm.setUserId(orderForm.getUserId());
        cartForm.setProductIdList(productIdList);

        return cartForm;
    }
}
